package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;


    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {

        // 防止支付信息重复保存
        PaymentInfo paymentInfoDB = this.lambdaQuery().eq(PaymentInfo::getOrderNo, orderNo).one();
        if(paymentInfoDB != null) return paymentInfoDB;

        paymentInfoDB = new PaymentInfo();

        // 构建本地交易信息
        paymentInfoDB.setUserId(userId);
        paymentInfoDB.setPaymentType(paymentType);
        paymentInfoDB.setOrderNo(orderNo);
        paymentInfoDB.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfoDB.setOutTradeNo(orderNo);
        if(paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)){
            // 订单
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在！");

            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
                throw new GuiguException(211, "订单状态错误！");
            }

            paymentInfoDB.setAmount(orderInfo.getOrderAmount());
            paymentInfoDB.setContent(orderInfo.getOrderTitle());
        }
        if(paymentType.equals(SystemConstant.PAYMENT_TYPE_RECHARGE)){
            // 充值
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "订单不存在！");

            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
                throw new GuiguException(211, "充值订单状态错误！");
            }

            paymentInfoDB.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfoDB.setContent("余额充值");
        }
        paymentInfoDB.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);

        this.save(paymentInfoDB);
        return paymentInfoDB;
    }

}
